class List {
    constructor() {
        // 获取商品列表
        this.getGoodsList();
    }
    /***********获取商品列表**************/
    async getGoodsList() {
        // 获取页面中的插入节点
        let nodes = this.$('.sk_bd ul')
        // console.log(nodes);
        //发送请求
        let res = await axios.get('http://localhost:8888/goods/list')
        // console.log(res);
        //获取其中的data和status
        let { data, status } = res;
        // console.log(data,status);
        //判断获取成功,否则返回
        if (data.code != 1 || status != 200) {
            // console.log(11111);
            return;
        }
        //遍历data中的内容,放入页面中
        let html = '';
        data.list.forEach(element => {
            // console.log(element);
            html += `<li class="sk_goods" data-id="${element.goods_id}">
			<a href="product.html?${element.goods_id}"><img src=${element.img_big_logo} alt=""></a>
			<h5 class="sk_goods_title">${element.title}</h5>
			<p class="sk_goods_price"><em>¥${element.current_price}</em> <del>￥${element.price}</del></p>
			<div class="sk_goods_progress">
				已售<i>${element.sale_type}</i>
				<div class="bar">
					<div class="bar_in"></div>
				</div>
				剩余<em>${element.goods_number}</em>件
			</div>
			<a href="#none" class="sk_goods_buy" onclick="List.clickBuy()">立即抢购</a>
		</li>`
        });
        nodes.innerHTML = html;
    }
    /* ****************点击购买******************** */
    static clickBuy() {
        // console.log(111111);
        console.log(window.event.target);
        //判断是否登陆,检查id和token
        //获取id和token,商品id
        let id = localStorage.getItem('id');
        let token = localStorage.getItem('token');
        let goodsId = window.event.target.parentNode.dataset.id;
        //拼接字符串
        let str = `id=${id}&goodsId=${goodsId}`;
        // console.log(goodsId);
        //如果不存在,就跳转至登陆界面
        if (!id || !token) {
            location.assign('login.html?comeFrom=list.html')
        } else {
            const AUTH_TOKEN = localStorage.getItem('token');
            axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
            axios.post('http://localhost:8888/cart/add', str)
                .then((res) => {
                    console.log(res);
                })
            //如果存在,就弹窗询问是或否前往购物车
            layer.confirm('是否前往购物车', {
                btn: ['现在就去', '再逛逛'] //按钮
            }, function (index) {
                // console.log(1111);
                location.assign('car.html');
                //手动关闭此弹窗
                layer.close(index);
            })
        }
    }
    /* ************自己做的获取节点**************** */
    $(ele) {
        let node = document.querySelectorAll(ele)
        return node.length == 1 ? node[0] : node;
    }
}
new List;